package com.renshine.swing.listener;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JTable;

import com.renshine.swing.model.BaseTableModel;

/**
 * 表格的删除，移动监听器
 * @author liuqiang
 *
 */
public class TBKeyAdapter extends KeyAdapter {
	private JTable table;
	private BaseTableModel model;
	
	public TBKeyAdapter(JTable table, BaseTableModel model) {
		super();
		this.table = table;
		this.model = model;
	}

	public void keyPressed(KeyEvent e) {
		 // 选中的行
		 int[] rows = table.getSelectedRows();
		 if(rows.length <= 0) return;
		 // 按下Delete键删除行
		 if(e.getKeyCode() == KeyEvent.VK_DELETE){
			 for (int i = rows.length -1 ; i >= 0 ; i--) {
				 model.removeRow(rows[i]);
			 }
		 }
		 // 上键进行移动
		 if(e.getKeyCode() == KeyEvent.VK_UP){
			 for (int i =0 ; i < rows.length ; i++) {
				if(rows[i] > 0){
					model.moveRow(rows[i], rows[i], rows[i] - 1);
				}
			 }	
		 }
		 // 下键进行移动
		 if(e.getKeyCode() == KeyEvent.VK_DOWN){
			 int rowCount = table.getRowCount();
			 for (int i = rows.length -1 ; i >= 0 ; i--) {
				 if(rows[i] + 1 < rowCount){
					 model.moveRow(rows[i], rows[i], rows[i] + 1);
				 }
			 }
		 }
	 }
}
